package com.xiaou.realm;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

/**
 * 实现限制尝试登陆的次数
 * @author xiaou
 *
 */
public class MyHashedCredentialsMatcher extends HashedCredentialsMatcher{
	
	// 缓存对象
	private Cache<String, AtomicInteger> passwordRetryCache ;
	
	public MyHashedCredentialsMatcher(CacheManager cacheManager) {
		passwordRetryCache = cacheManager.getCache("passwordRetryCache");
	}
	
	@Override
	public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
		
		String username = (String) token.getPrincipal();
		// 1.获取输入错误的次数
		AtomicInteger retryCount = passwordRetryCache.get(username);
		// 2.判断是否是第一次，因为第一次的话retryCount为null
		if(null == retryCount) {
			retryCount = new AtomicInteger(0);
			passwordRetryCache.put(username, retryCount);
		}
		// 3.判断密码输入超过的次数 incrementAndGet 先做++ 然后获得retryCount
		if(retryCount.incrementAndGet()>3) {
			throw new ExcessiveAttemptsException("尝试次数过多");
		}
		// 4.进行密码校验
		boolean match = super.doCredentialsMatch(token, info);
		// 5.如果校验通过则清除缓存
		if(match) {
			passwordRetryCache.remove(username);
		}
		
		return match;
	}
	

}
